package com.qn.util;

import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.net.HttpCookie;

public class CookieUtil {
    private static final String ZH = "zh";
    private static final String EN = "en";
    private static final String CN = "cn";
    private static final String US = "us";
    private static final String ZH_CN = "zh_cn";
    private static final String LANG = "lang_key";

    public CookieUtil() {
    }

    public static String getLanguage() {
        return decideLocaleInfoFromCookie("en", "zh");
    }

    public static String getCountry() {
        return decideLocaleInfoFromCookie("us", "cn");
    }

    private static String decideLocaleInfoFromCookie(String defaultEnValue, String cnValue) {
        HttpServletRequest request = getRequest();
        Cookie[] cookies = null;
        if (request != null) {
            cookies = getCookies(request);
        }

        if (cookies != null) {
            Cookie[] var4 = cookies;
            int var5 = cookies.length;

            for (int var6 = 0; var6 < var5; ++var6) {
                Cookie cookie = var4[var6];
                if ("lang_key".equals(cookie.getName()) && "zh_cn".equals(cookie.getValue())) {
                    return cnValue;
                }
            }
        }

        return defaultEnValue;
    }

    public static Cookie[] getCookies(HttpServletRequest request) {
        Cookie[] cookies = null;
        if (request.getCookies() != null) {
            cookies = request.getCookies();
        } else {
            String cookieStr = request.getHeader("cookie");
            if (StringUtils.isNotBlank(cookieStr)) {
                cookies = HttpCookie.parse(cookieStr).stream().map((httpCookie) -> {
                    return new Cookie(httpCookie.getName(), httpCookie.getValue());
                }).toArray((x$0) -> {
                    return new Cookie[x$0];
                });
            }
        }

        return cookies;
    }

    public static String getCountryByLanguage(String language) {
        String country = "us";
        if ("zh".equals(language)) {
            country = "cn";
        }

        return country;
    }

    public static HttpServletRequest getRequest() {
        HttpServletRequest request = null;
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        if (attributes != null && attributes instanceof ServletRequestAttributes) {
            request = ((ServletRequestAttributes) attributes).getRequest();
        }

        return request;
    }
}

